<template>
  <div class="app-container">
    <el-container>
      <el-aside width="200px">
        <el-scrollbar>
          <div class="search-container left-bb">
            <el-tree
              :data="deptTreeData"
              :props="defaultProps"
              :default-expand-all="true"
              @node-click="handleNodeClick"
              :highlight-current="true"
            />
          </div>
        </el-scrollbar>
      </el-aside>
      <el-main>
        <div class="search-container right-bb">
          <el-form inline label-width="68px" ref="queryFromRef" :model="queryParams">
            <el-form-item label="登录名">
              <el-input v-model="queryParams.username" placeholder="" />
            </el-form-item>

            <el-form-item label="姓名">
              <el-input v-model="queryParams.realName" placeholder="" />
            </el-form-item>

            <el-form-item>
              <el-button
                class="filter-item"
                v-hasPerm="['sys:user:query']"
                type="primary"
                @click="handleQuery"
              >
                <i-ep-search />
                搜索
              </el-button>
              <el-button
                class="filter-item"
                v-hasPerm="['sys:user:query']"
                @click="handleResetQuery"
              >
                <i-ep-refresh />重置
              </el-button>
              <el-button
                class="filter-item"
                v-hasPerm="['sys:user:add']"
                type="success"
                @click.stop="handleOpenDialog()"
              >
                <i-ep-plus />
                新增
              </el-button>
              <!-- 新增下载按钮 -->
              <el-button
                class="filter-item"
                v-hasPerm="['sys:user:download']"
                @click="handleDownload"
              >
                <i-ep-download />
                <!-- 假设存在下载图标组件 -->
                下载
              </el-button>
              <el-button class="filter-item" v-hasPerm="['sys:user:upload']" @click="handleUpload">
                <i-ep-upload />
                <!-- 假设存在上传图标组件 -->
                上传Excel
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <el-table v-loading="loading" stripe :data="list" style="width: 100%">
            <!-- <el-table-column label="ID" width="50" prop="id" /> -->
            <el-table-column label="登录名" width="200" prop="username" />
            <el-table-column label="姓名" width="200" prop="realName" />
            <el-table-column label="性别" width="100" prop="gender" />

            <el-table-column label="电话" width="200" prop="phone" />
            <el-table-column label="邮箱" width="200" prop="email" />

            <el-table-column label="状态" width="100" prop="enabled">
              <template #default="scope">
                <el-tag v-if="scope.row.enabled" type="success">使用</el-tag>
                <el-tag v-else type="info">禁用</el-tag>
              </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" width="300">
              <template #default="scope">
                <el-button
                  v-hasPerm="['sys:user:update']"
                  type="primary"
                  link
                  size="small"
                  @click.stop="handleOpenDialog(scope.row.id)"
                >
                  <i-ep-edit />
                  修改
                </el-button>

                <el-button
                  v-hasPerm="['sys:user:resetPwd']"
                  type="primary"
                  link
                  size="small"
                  @click.stop="handleResetPwd(scope.row.id)"
                >
                  <i-ep-user />
                  重置密码
                </el-button>

                <el-button
                  v-hasPerm="['sys:user:delete']"
                  type="danger"
                  link
                  size="small"
                  @click.stop="handleDelete(scope.row.id)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-main>
    </el-container>

    <el-drawer v-model="dialog.visible" :title="dialog.title" @close="handleCloseDialog" size="50%">
      <el-form ref="addFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="登录名" prop="username">
          <el-input v-model="formData.username" placeholder="" />
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="formData.realName" placeholder="" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="formData.gender">
            <el-radio value="男">男性</el-radio>
            <el-radio value="女">女性</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="" />
        </el-form-item>

        <el-form-item label="电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="" />
        </el-form-item>

        <el-form-item label="主机构" prop="deptId">
          <el-tree-select
            v-model="formData.deptId"
            :data="deptTreeData"
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="其他机构" prop="deptIdList">
          <el-tree-select
            multiple
            v-model="formData.deptIdList"
            :data="deptTreeData"
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="主岗位" prop="postId">
          <el-select v-model="formData.postId">
            <el-option
              v-for="item in postList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="其他岗位" prop="postIdList">
          <el-select multiple v-model="formData.postIdList">
            <el-option
              v-for="item in postList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="角色" prop="roleIdList">
          <el-select multiple v-model="formData.roleIdList">
            <el-option
              v-for="item in roleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="formData.remark" placeholder="" />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="formData.enabled">
            <el-radio :value="true">有效</el-radio>
            <el-radio :value="false">无效</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
defineOptions({
  name: 'User',
  inheritAttrs: false
})

import { ElForm, ElTable } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'
const BASE_URL = '/api/yyplatform/admin/sys/user/'
import axios from 'axios'
import { saveAs } from 'file-saver'

const list = ref([])
const total = ref(0)
const loading = ref(false)

const postList = ref([])
const deptTreeData = ref([])
const roleList = ref([])
const defaultProps = ref({
  children: 'children',
  label: 'label'
})

const deptId = ref(0)

const addFormRef = ref(ElForm)
const formData = ref({
  id: '',
  username: '',
  realName: '',
  phone: '',
  email: '',
  gender: '男',
  remark: '',
  enabled: true,
  deptIdList: [],
  deptId: null,
  postId: null,
  postIdList: [],
  roleIdList: []
})
const queryFromRef = ref()
const dialog = ref({
  title: '',
  visible: false
})

const queryParams = ref({
  name: '',
  code: '',
  pageNum: 1,
  pageSize: 20
})

const rules = ref({
  username: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  phone: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  email: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  realName: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  roleIdList: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  postId: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})

function handleNodeClick(node) {
  console.log('handleNodeClick', node)
  deptId.value = node.id
  handleQuery()
}

function handleCloseDialog() {
  dialog.value.visible = false
  dialog.value.title = '添加人员'
  formData.value = {
    id: '',
    username: '',
    realName: '',
    phone: '',
    email: '',
    gender: '男',
    remark: '',
    enabled: true,
    deptIdList: [],
    deptId: null,
    postId: null,
    postIdList: [],
    roleIdList: []
  }
}

// =============================================================

function handleDownload() {
  let url = `/api/yyplatform/admin/sys/user/download`
  let params = Object.keys(queryParams.value)
    .map((key) => key + '=' + queryParams.value[key])
    .join('&')

  url = url + '?' + params

  console.log('url====>', url)
  //window.open(url)
  request({
    method: 'get',
    url: url,
    responseType: 'blob'
  })
    .then((response) => {
      const blob = new Blob([response.data])
      saveAs(blob, '下载.xls')
    })
    .catch((error) => {
      console.error('下载失败', error)
    })
}

// 新增上传处理函数
async function handleUpload() {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.xlsx,.xls'
  input.onchange = async (e) => {
    const file = e.target.files[0]
    if (file) {
      const formData = new FormData()
      formData.append('file', file)
      try {
        const res = await request({
          url: `${BASE_URL}/upload`,
          method: 'post',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        ElMessage.success('上传成功')
        await handleQuery() // 上传成功后刷新列表
      } catch (error) {
        console.error('上传失败', error)
        ElMessage.error('上传失败，请重试')
      }
    }
  }
  input.click()
}

// =============================================================

async function handleOpenDialog(id) {
  if (id) {
    let res = await request({
      url: `${BASE_URL}/get?id=${id}`,
      method: 'get'
    })

    let postListRes = await request({
      url: `/api/yyplatform/admin/sys/post/options`,
      method: 'get'
    })
    postList.value = postListRes

    let roleListRes = await request({
      url: `/api/yyplatform/admin/sys/role/options`,
      method: 'get'
    })
    roleList.value = roleListRes

    formData.value = res
    dialog.value.visible = true
    dialog.value.title = '修改人员'
  } else {
    let resDeptTreeData = await request({
      url: `/api/yyplatform/admin/sys/dept/options`,
      method: 'get'
    })
    deptTreeData.value = resDeptTreeData

    let roleListRes = await request({
      url: `/api/yyplatform/admin/sys/role/options`,
      method: 'get'
    })
    roleList.value = roleListRes

    let postListRes = await request({
      url: `/api/yyplatform/admin/sys/post/options`,
      method: 'get'
    })
    postList.value = postListRes

    dialog.value.visible = true
    dialog.value.title = '添加人员'
    formData.value = {
      id: '',
      username: '',
      realName: '',
      phone: '',
      email: '',
      gender: '男',
      remark: '',
      enabled: true,
      deptIdList: [],
      deptId: null,
      postId: null,
      postIdList: [],
      roleIdList: []
    }
  }
}
async function submitForm() {
  addFormRef.value.validate(async (isValid) => {
    if (isValid) {
      const id = formData.value.id
      if (id) {
        let updateRes = await request({
          url: `${BASE_URL}/update`,
          method: 'post',
          data: formData.value
        })
        ElMessage.success('修改成功')
        handleCloseDialog()
        await handleQuery()
      } else {
        let addRes = await request({
          url: `${BASE_URL}/save`,
          method: 'post',
          data: formData.value
        })
        ElMessage.success('添加成功')
        handleCloseDialog()
        await handleQuery()
      }
    }
  })
}

async function handleResetPwd(id) {
  ElMessageBox.confirm('确认执行该操作吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    //
    let updateRes = await request({
      url: `${BASE_URL}/resetPwd?id=${id}`,
      method: 'post'
    })
    ElMessage.success('重置密码成功.')
  })
}
function handleDelete(id) {
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request({
      url: `${BASE_URL}/delete`,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: {
        id: id
      }
    }).then(async () => {
      await handleQuery()
    })
  })
}

async function handleResetQuery() {
  await handleQuery()
}

async function loadDeptData() {
  let resDeptTreeData = await request({
    url: `/api/yyplatform/admin/sys/dept/options`,
    method: 'get'
  })
  deptTreeData.value = resDeptTreeData
}

async function handleQuery() {
  console.log(queryParams.value, 'queryParams')

  loading.value = true

  let queryRes = await request({
    url: `${BASE_URL}/query`,
    method: 'get',
    params: {
      deptId: deptId.value,
      ...queryParams.value
    }
  })

  loading.value = false
  list.value = queryRes.content
  total.value = parseInt(queryRes.totalElements)
}

async function handleRole(id) {
  console.log('handleRole', id)
}

onMounted(async () => {
  await handleQuery()
  await loadDeptData()
})
</script>
<style>
.left-bb {
  min-height: 400px;
}
.right-bb {
  margin-top: -18px;
}
</style>
